package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.reggie.entity.Category;
import com.itheima.reggie.entity.Dish;
import com.itheima.reggie.entity.DishCategoryCash;
import com.itheima.reggie.entity.OrderDetail;
import com.itheima.reggie.service.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

@Slf4j
@RestController
@RequestMapping("/statics")
public class StaticsController {
    @Autowired
    private CategoryService categoryService;
    @Autowired
    private OrdersService ordersService;
    @Autowired
    private OrderDetailService orderDetailService;
    @Autowired
    private DishService dishService;
    @Autowired
    private SetmealService setmealService;

    @GetMapping("/dishCash")
    public List<DishCategoryCash> dishCash() {
        ArrayList<DishCategoryCash> dishCategoryCashes = new ArrayList<>();
        LambdaQueryWrapper<Category> qw = new LambdaQueryWrapper<>();
        qw.eq(Category::getType, 1);
        List<Category> categoryList = categoryService.list(qw);
        for (Category category : categoryList) {
            DishCategoryCash categoryCash = new DishCategoryCash();
            categoryCash.setName(category.getName());
            dishCategoryCashes.add(categoryCash);
        }
        LambdaQueryWrapper<OrderDetail> oqw = new LambdaQueryWrapper<>();
        oqw.isNotNull(OrderDetail::getDishId);
        List<OrderDetail> orderDetails = orderDetailService.list(oqw);
        for (OrderDetail orderDetail : orderDetails) {
            BigDecimal amount = orderDetail.getAmount();
            Long dishId = orderDetail.getDishId();
            Dish dish = dishService.getById(dishId);
            Long categoryId = dish.getCategoryId();
            Category category = categoryService.getById(categoryId);
            for (DishCategoryCash dishCategoryCash : dishCategoryCashes) {
                if (category.getName().equals(dishCategoryCash.getName())){
                    BigDecimal value = dishCategoryCash.getValue();
                    if (value!=null){
                         amount= amount.add(value);
                    }
                    dishCategoryCash.setValue(amount);
                }
            }
        }
        return dishCategoryCashes;
    }
}
